<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Illuminate\Support\Facades\Redis;

class TemHuiPreController extends Controller
{
    public function log(Request $request){
        $data = DB::table('a_env_info')->where(['hb6303_id'=>$request->id])->orderBy('id','desc')->get();
        return view('admin.temHuiPre.log',compact('data'));
    }
    public function exportLog(Request $request){
        set_time_limit(0);
        ini_set('max_execution_time', 0);
        ini_set('memory_limit', '-1');
        $id = $request->id;
        $info = DB::table('a_hb6303')->find($id);
        if(!$info){
            // dd(request()->all());
            return '设备终端不存在！';
        }
        $data = DB::table('a_env_info')->where(['hb6303_id'=>$id])->orderBy('id','desc')->get();
        $dataArray = [['记录时间','温度（℃）','湿度（%）','大气压（kPa）']];
        foreach ($data as $item) {
            $dataArray[] = [$item->time,$item->temp,$item->humi,$item->pressure];
        }
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();
        $worksheet->setTitle('最近7天历史记录');
        $worksheet->fromArray($dataArray, null, 'A1');
        $worksheet->getColumnDimension('A')->setWidth(20);
        $worksheet->getColumnDimension('B')->setWidth(10);
        $worksheet->getColumnDimension('C')->setWidth(10);
        $worksheet->getColumnDimension('D')->setWidth(15);
        // dd($worksheet->getPageSetup());
        $styleArray = [
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
            ],
            'borders' => [
                'allBorders' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
                ],
            ],
        ];
        $worksheet->getStyle('A1:D'.($data->count()+1))->applyFromArray($styleArray);
        $worksheet->getPageSetup()->setHorizontalCentered(true)->setRowsToRepeatAtTop([1,1]);
        $spreadsheet->setActiveSheetIndex(0);
        $file_name = $info->pos.$info->dev_num.'.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename='.urlencode($file_name));
        header('Cache-Control: max-age=0');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
        exit;
    }
    //温湿度气压计 列表展示
    public function index(Request $request) {
        if($request->expectsJson()) {
            //ajax请求
            //温湿度气压计 列表 datatable的ajax 加载
            $sql = "SELECT
                        *
                    FROM
                        `a_hb6303` AS `a`
                    LEFT JOIN (
                        SELECT
                            max(id) as env_id,
                            hb6303_id
                        FROM
                            a_env_info
                        GROUP BY
                            hb6303_id
                    ) AS `b` ON `a`.`id` = `b`.`hb6303_id`
                    LEFT JOIN (
                        SELECT
                            id as c_id,temp,humi,pressure,time as last_time
                        FROM
                            a_env_info
                    ) AS `c` ON `c`.`c_id` = `b`.`env_id` ";
            $data = DB::select($sql);
            $newData = [];
            if(count($data) > 0) {
                if(config('constant.is_lan')){
                    $redis = Redis::connection('public');
                    $qingping_device_list = $redis->get('qingping_device_list');
                    $arr_device_list = json_decode($qingping_device_list, true);
                    $arr_device_list = $arr_device_list['devices'];
                }else{
                    $arr_device_list = [];
                }
                

                foreach($data as $key => $val) {
                    # code...
                    $newData[$key]['id'] = $val->id; //id
                    $newData[$key]['dev_num'] = $val->dev_num; //设备编号
                    $newData[$key]['pos'] = $val->pos; //监测位置
                    $newData[$key]['battery'] = '--'; //电量
                    $newData[$key]['signal'] = '--'; //信号
                    $newData[$key]['status'] = '--'; //状态
                    $newData[$key]['version'] = '--'; //固件版本
                    $newData[$key]['last_time'] = $val->last_time; //上次联网上报
                    $newData[$key]['temp'] = sprintf("%01.1f",$val->temp); //温度
                    $newData[$key]['humi'] = $val->humi; //湿度
                    $newData[$key]['pressure'] = $val->pressure; //大气压

                    if(strlen($val->dev_num) === 12) {
                        # 设备编号 长度为12位，说明设备是青萍的
                        foreach($arr_device_list as $v) {
                            # code...
                            $mac = $v['info']['mac'];
                            if($mac === $val->dev_num) {
                                # code...
                                $newData[$key]['battery'] = $v['data']['battery']['value']; //电量
                                $newData[$key]['version'] = $v['info']['version']; //固件版本
                                $newData[$key]['temp'] = sprintf("%01.1f",$v['data']['temperature']['value']); //温度
                                $newData[$key]['humi'] = $v['data']['humidity']['value']; //湿度
                                $newData[$key]['pressure'] = $v['data']['pressure']['value']; //大气压
                                $timestamp = $v['data']['timestamp']['value'];
                                $newData[$key]['last_time'] = date("Y-m-d H:i:s", $timestamp); //上次联网上报
                                if((time() - $timestamp) > 60*25) {
                                    # 此设备已离线
                                    $newData[$key]['status'] = '离线';
                                }
                                else {
                                    $newData[$key]['status'] = '在线';
                                    $newData[$key]['signal'] = isset($v['data']['signal']) ? $v['data']['signal']['value'] : '--'; //信号
                                }
                                break;
                            }
                        }
                    }
                }
            }
            $jsonData['data'] = $newData;
            return response()->json($jsonData);
        }
        else {
            return view('admin.temHuiPre.index');
        }
    }

    //温湿度气压计 删除
    public function del(Request $request) {
        $id = $request->id;
        //  delete 返回受影响的行数
        $result = DB::table('a_hb6303')->where('id', $id)->delete();
        //由于框架自身不支持响应bool值，所以转化一种形式
        return $result >= 0 ? '1' : '0';
    }

    //温湿度气压计 添加
    public function add(Request $request) {
        if($request->isMethod('POST')) {
            $post_data = $request->except(['_token']);
            // $post_data['dev_num'] = strtoupper($post_data['dev_num']); //转成大写字母
            $result = DB::table('a_hb6303')->insert($post_data);
            //由于框架自身不支持响应bool值，所以转化一种形式
            return $result ? '1' : '0';
        }
        else {
            return view('admin.temHuiPre.add');
        }
    }


    //温湿度气压计 修改
    public function edit(Request $request) {
        $id = $request->id;
        if($request->isMethod('POST')) {
            $post_data = $request->except(['_token','dev_num']);
            $result = DB::table('a_hb6303')->where('id', $id)->update($post_data);
            //由于框架自身不支持响应bool值，所以转化一种形式
            return $result ? '1' : '0';
        }
        else {
            //查询要修改的温湿度气压计 信息
            $temHuiPre_info = DB::table('a_hb6303')->find($id);
            // dd($temHuiPre_info);
            return view('admin.temHuiPre.edit', compact('temHuiPre_info'));
        }
    }
}
